package com.example.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.Constants;
import com.example.springboot.dto.LoginDTO;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.IEmailService;
import com.example.springboot.utils.SensitiveWordUtil;
import com.example.springboot.utils.TokenUtils;
import com.vdurmont.emoji.EmojiManager;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.common.Result;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.example.springboot.service.IUserService;
import com.example.springboot.entity.User;

import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
    public class UserController {
    
    @Resource
    private IUserService userService;
    @Resource
    private IEmailService emailService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody User user) throws IOException {
        if (user.getNickname() != null && !user.getNickname().equals(SensitiveWordUtil.sensitiveHelper(user.getNickname())))
            throw new ServiceException(Constants.CODE_600,"昵称含敏感词汇，请重新输入");
        if (EmojiManager.containsEmoji(user.getNickname()))
            throw new ServiceException(Constants.CODE_600,"昵称含特殊字符，请重新输入");
        if (user.getIntroduction() != null && !user.getIntroduction().equals(SensitiveWordUtil.sensitiveHelper(user.getIntroduction())))
            throw new ServiceException(Constants.CODE_600,"自我介绍含敏感词汇，请重新输入");
        return Result.success(userService.saveOrUpdate(user));
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(userService.removeById(id));
    }

    //根据id批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(userService.removeByIds(ids));
    }

    //查找所有
    @GetMapping
    public Result findAll() {
        return Result.success(userService.list());
    }

    //根据id查找
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(userService.getById(id));
    }

    //根据id查找个人主页
    @GetMapping("/home")
    public Result getHome(@RequestParam Integer id) {
        return Result.success(userService.getHome(id));
    }

    //查看当前用户主页
    @GetMapping("/getMyHome")
    public Result getMyHome() {
        return Result.success(userService.getHome(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()));
    }

    //查找当前用户信息
    @GetMapping("/getMyInfo")
    public Result getMyInfo() {
        return Result.success(userService.getById(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()));
    }

    //获取个人中心评论内容
    @GetMapping("/CommentsCenter")
    private Result getCommentsCenter() {
        return Result.success(userService.getCommentsCenter(Objects.requireNonNull(TokenUtils.getCurrentUser()).getId()));
    }

    //根据邮箱获取验证码
    @GetMapping("/getCode")
    private Result getCode(@RequestParam String to, HttpSession httpSession){
        if (StrUtil.isBlank(to))
            return Result.error(Constants.CODE_600,"请输入邮箱");
        String code = emailService.sendEmail(to);
        httpSession.setAttribute("email",to);
        httpSession.setAttribute("code",code);
        httpSession.setAttribute("time",new Date());
        httpSession.setMaxInactiveInterval(5 * 60); //设置过期时间
        return Result.success("验证码已发送" + code);
    }

    //根据验证码登录
    @GetMapping("/setPassword")
    private Result setPassword(@RequestParam String email,
                               @RequestParam String password,
                               @RequestParam String code,
                               HttpServletRequest request){
        return userService.setPassword(email,code,password,request);
    }

    //根据验证码登录
    @GetMapping("/loginByCode")
    private Result loginByCode(@RequestParam String email,@RequestParam String code, HttpServletRequest request){
        return userService.loginByCode(email,code,request);
    }

    //根据密码登录
    @GetMapping("/loginByPassword")
    private Result loginByPassword(@RequestParam String email,@RequestParam String password){
        return userService.loginByPassword(email,password);
    }

    //首次第三方登录
    @GetMapping("/firstLoginFromPlatform")
    private Result firstLoginFromPlatform(@RequestParam String email,@RequestParam String username,@RequestParam String code,HttpServletRequest request) throws IOException {
        return userService.firstLoginFromPlatform(email,username,code,request);
    }

    //非首次第三方登录
    @GetMapping("/loginFromPlatform")
    private Result loginFromPlatform(@RequestParam String email,@RequestParam String username){
        return userService.loginFromPlatform(email,username);
    }

    //根据验证码注册
    @PostMapping("/register")
    private Result register(@RequestBody LoginDTO loginDTO, HttpServletRequest request) throws IOException {
        return userService.register(loginDTO,request);
    }

    //用户修改头像
    @PostMapping("/updateAvatar")
    private Result updateAvatar(@RequestBody Map<String, String> urlMap){
        return Result.success(userService.updateAvatar(urlMap.get("url")));
    }

    //管理员获取待审核头像的用户列表
    @GetMapping("/getAvatars")
    private Result getAvatars(@RequestParam(defaultValue = "1") int PageNum,
                              @RequestParam(defaultValue = "5") int PageSize){
        return Result.success(userService.getAvatars(PageNum,PageSize));
    }

    //管理员审核通过头像
    @GetMapping("/publishAvatar")
    private Result publishAvatar(@RequestParam Integer id, @RequestParam String url) {
        return userService.publishAvatar(id,url);
    }

    //管理员审核打回头像
    @GetMapping("/unPublishAvatar")
    private Result unPublishAvatar(@RequestParam Integer id, @RequestParam String url) {
        return userService.unPublishAvatar(id,url);
    }

    //获取传入token对应用户的用户名、昵称、头像
    @GetMapping("/getByToken")
    private Result getByToken(@RequestParam String token){
        return Result.success(userService.getByToken(token));
    }

    //根据用户名、昵称、电话分页查询
    @GetMapping("/findPageByUsername")
    public Result findPageByUsername(@RequestParam(defaultValue = "1") int PageNum,
                                     @RequestParam(defaultValue = "5") int PageSize,
                                     @RequestParam(defaultValue = "") String username,
                                     @RequestParam(defaultValue = "") String nickname) {

        return userService.findPage(PageNum,PageSize,username,nickname);
    }
}

